package com.cloudcc.mobile.adapter;

import java.io.File;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.cloudcc.mobile.util.ImageUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.photo.Constants;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;


public class AtContaxtAdapter extends BaseAdapter implements SectionIndexer{
	private List<CoworkerEntity> list = null;
	private Context mContext;
	public AtContaxtAdapter(Context mContext, List<CoworkerEntity> list) {
		this.mContext = mContext;
		this.list = list;
	}
	
	/**
	 * 当ListView数据发生变化时,调用此方法来更新ListView
	 * @param list
	 */
	public void updateListView(List<CoworkerEntity> list){
		this.list = list;
		notifyDataSetChanged();
	}

	public int getCount() {
		return this.list.size();
	}

	public CoworkerEntity getItem(int position) {
		return list.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	@SuppressWarnings("unused")
	public View getView(final int position, View view, ViewGroup arg2) {
		ViewHolder viewHolder = null;
		final CoworkerEntity mContent = list.get(position);
		if (view == null) {
			viewHolder = new ViewHolder();
			view = LayoutInflater.from(mContext).inflate(R.layout.chat_constacts_item, null);
			viewHolder.tvTitle = (TextView) view.findViewById(R.id.title);
			viewHolder.tvLetter = (TextView) view.findViewById(R.id.catalog);
			viewHolder.phone = (ImageView) view.findViewById(R.id.chat_contaxt_phone);
			viewHolder.message = (ImageView) view.findViewById(R.id.chat_contaxt_mes);
			viewHolder.guanzhu = (ImageView) view.findViewById(R.id.chat_contaxt_guanzhu);
			viewHolder.icon = (ImageView) view.findViewById(R.id.chat_contact_icon);
			viewHolder.box=(CheckBox)view.findViewById(R.id.checkBox1);
			view.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) view.getTag();
		}
		//根据position获取分类的首字母的Char ascii值
		int section = getSectionForPosition(position);
		//如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
		if(position == getPositionForSection(section)){
			viewHolder.tvLetter.setVisibility(View.VISIBLE);
			viewHolder.tvLetter.setText(mContent.getSortLetters());
		}else{
			viewHolder.tvLetter.setVisibility(View.GONE);
		}

		String uri=UrlTools.getTopImage(mContent.getId());
		String icon=mContent.getId()+".png";
		String iconpath=Tools.getImagePath("/CloudCC/UserIcon/")+"/"+icon;
		File file=new File(iconpath);
		if(file.exists()){
			//					Constants.imageLoader.displayImage("file://" + iconpath, viewHolder.icon, Constants.Contact_options);
			viewHolder.icon.setImageBitmap(ImageUtils.loadBitmap(iconpath));
		}else{
			//			ImageLoader.getInstance().displayImage(uri, viewHolder.icon, Constants.Contact_options);
			ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener(icon);
			ImageLoader.getInstance().displayImage(uri, viewHolder.icon, Constants.Contact_options,animateFirstListener);	
		}

		viewHolder.tvTitle.setText(this.list.get(position).getName());
		if(mContent.getMobile()==null||mContent.getMobile().equals("")){
			viewHolder.phone.setVisibility(View.INVISIBLE);
			viewHolder.message.setVisibility(View.INVISIBLE);
		}else{
			viewHolder.phone.setVisibility(View.VISIBLE);
			viewHolder.message.setVisibility(View.VISIBLE);
		}
		viewHolder.phone.setOnClickListener(new OnClickListener() {@Override	public void onClick(View v) {
			String mobile=mContent.getMobile();
			Tools.showInfo(mContext, "打电话"+mobile);
			String tel="tel:"+mobile;
			Uri uri=Uri.parse(tel);
			Intent intent=new Intent(Intent.ACTION_CALL,uri);
			mContext.startActivity(intent); 
		}});
		viewHolder.message.setOnClickListener(new OnClickListener() {@Override	public void onClick(View v) {
			String mobile=mContent.getMobile();
			Tools.showInfo(mContext, "发短信"+mobile);
			Uri smsToUri = Uri.parse("smsto:"); 
			Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri); 
			sendIntent.putExtra("address",mobile);   //电话号码，这行去掉的话，默认就没有电话
			sendIntent.setType("vnd.android-dir/mms-sms"); 
			mContext.startActivity(sendIntent);
		}});

		boolean isSelect=AppContext.getInstance().contactmap.get(position) == null ? false : true;
		if(isSelect){
//			viewHolder.box.setVisibility(View.VISIBLE);
			viewHolder.box.setChecked(isSelect);
		}else{
//			viewHolder.box.setVisibility(View.INVISIBLE);
			viewHolder.box.setChecked(isSelect);
		}
		viewHolder.phone.setVisibility(View.GONE);
		viewHolder.message.setVisibility(View.GONE);
		viewHolder.guanzhu.setVisibility(View.GONE);
		return view;
	}
	
	class ViewHolder {
		TextView tvLetter;
		TextView tvTitle;
		ImageView phone;
		ImageView message;
		ImageView guanzhu;
		ImageView icon;
		CheckBox box;
	}


	/**
	 * 根据ListView的当前位置获取分类的首字母的Char ascii值
	 */
	public int getSectionForPosition(int position) {
		return list.get(position).getSortLetters().charAt(0);
	}

	/**
	 * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
	 */
	public int getPositionForSection(int section) {
		for (int i = 0; i < getCount(); i++) {
			String sortStr = list.get(i).getSortLetters();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) {
				return i;
			}
		}

		return -1;
	}

	/**
	 * 提取英文的首字母，非英文字母用#代替。
	 * 
	 * @param str
	 * @return
	 */
	private String getAlpha(String str) {
		String  sortStr = str.trim().substring(0, 1).toUpperCase();
		// 正则表达式，判断首字母是否是英文字母
		if (sortStr.matches("[A-Z]")) {
			return sortStr;
		} else {
			return "#";
		}
	}
	private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
		private String id;
		public AnimateFirstDisplayListener(String imageId){
			this.id=imageId;
		}
		static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
		@Override
		public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
					ImageUtils.saveImage("/CloudCC/UserIcon",id, loadedImage);//图片保存
				}
			}
		}
	}
	@Override
	public Object[] getSections() {
		return null;
	}


}